package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.WmMaterialMapper;
import com.zhentao.mapper.WmNewsMaterialMapper;
import com.zhentao.model.common.dtos.PageResponseResult;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.common.wemedia.*;
import com.zhentao.service.WmNewsAutoScanService;
import com.zhentao.service.WmNewsService;
import com.zhentao.mapper.WmNewsMapper;
import com.zhentao.service.WmNewsTaskService;
import com.zhentao.utils.wemedia.WmThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
* @author EWEWW
* @description 针对表【wm_news(自媒体图文内容信息表)】的数据库操作Service实现
* @createDate 2024-06-07 10:07:31
*/
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews>
    implements WmNewsService{
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsTaskService newsTaskService;

    @Resource
    private KafkaTemplate kafkaTemplate;
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.分页参数检查
        dto.checkParam();
        //获取当前登录人的id
        WmUser wmUser = WmThreadLocalUtil.getUser();
        if(wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.分页查询
        Page<WmNews> page=new Page<>(dto.getPage(), dto.getSize());
        QueryWrapper<WmNews> queryWrapper = new QueryWrapper<>();
        //状态查询
        queryWrapper.lambda().eq(dto.getStatus()!=null, WmNews::getStatus,dto.getStatus());
        //频道查询
        queryWrapper.lambda().eq(dto.getChannelId()!=null, WmNews::getChannelId,dto.getChannelId());
        //关键字查询
        queryWrapper.lambda().like(dto.getKeyword()!=null, WmNews::getTitle,dto.getKeyword());
        //根据用户查询
        queryWrapper.lambda().eq(WmNews::getUserId,wmUser.getId());
        //按照时间倒叙
        queryWrapper.lambda().orderByDesc(WmNews::getCreatedTime);
        //根据时间范围查询
        if(dto.getBeginPubDate() !=null && dto.getEndPubDate() != null){
            queryWrapper.lambda().between(WmNews::getPublishTime, dto.getBeginPubDate(),dto.getEndPubDate());
        }
        page = wmNewsMapper.selectPage(page, queryWrapper);
        //3.返回结果
        ResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        //1.条件判断
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存或修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        //type数据库使用的是tinyint,0-255,不能使用负载，前端传递是-1
        if(dto.getType() == -1){
            dto.setType((short)4);
        }
        wmNews.setType(Integer.valueOf(dto.getType()));

        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((int) 1);

        //获取文章的封面图片
        if(dto.getImages() != null && dto.getImages().size()>0){
            //前端传过来的是json格式，数据库里面的是使用，隔开的图片
            String imaStr = StringUtils.join(dto.getImages(),",");
            wmNews.setImages(imaStr);
        }

        //判断id是否存在，如果不存在执行新增操作，如果已经存在了，执行修改操作：
        //id 是前端页面传递过来的
       if(wmNews.getId() == null){
           //新增
           wmNewsMapper.insert(wmNews);
       }else { //修改
           //首先删除文章与素材的关系，在修改
           QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
           queryWrapper.lambda().eq(WmNewsMaterial::getNewsId,wmNews.getId());
           wmNewsMaterialMapper.delete(queryWrapper);
           //执行修改操作
           wmNewsMapper.updateById(wmNews);
       }

       if(dto.getType() != 4){//封面图片是自己上传的
           //3.绑定关系
           List<String> images = dto.getImages();
           if(images !=null && images.size() > 0){
               //通过查询图片的url获取素材的id
               QueryWrapper<WmMaterial> wmMaterialQueryWrapper = new QueryWrapper<>();
               wmMaterialQueryWrapper.lambda().in(WmMaterial::getUrl,images);
               List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(wmMaterialQueryWrapper);
               //把素材的id存入list里面
               List<Integer> ids = new ArrayList<>();
               for (WmMaterial wmMaterial : wmMaterialList) {
                   ids.add(wmMaterial.getId());
               }
               //素材与内容进行绑定
               wmNewsMaterialMapper.saveRelations(ids, wmNews.getId(),(short)0);
           }
        }else{  //封面图片需要从内容里面获取
           //把文章中内容的图片给提取出来
           List<Map> maps = JSON.parseArray(dto.getContent(),Map.class);
           List<String> materials = new ArrayList<>();
           for (Map map : maps) {
               if(map.get("type").equals("image")){
                   String imgUrl = (String) map.get("value");
                   materials.add(imgUrl);
               }
           }

           if(materials != null && materials.size() > 0){
               //修改封面图片
               String imgs = StringUtils.join(materials,",");
               wmNews.setImages(imgs);
               wmNewsMapper.updateById(wmNews);

               //绑定关系

               //通过查询图片的url 获取素材的id
               QueryWrapper<WmMaterial> wmMaterialQueryWrapper = new QueryWrapper<>();
               wmMaterialQueryWrapper.lambda().in(WmMaterial::getUrl, materials);
               List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(wmMaterialQueryWrapper);

               //把素材的id存入list里面
               List<Integer> ids = new ArrayList<>();
               for (WmMaterial wmMaterial : wmMaterialList) {
                   ids.add(wmMaterial.getId());
               }
               //素材与内容进行绑定
               wmNewsMaterialMapper.saveRelations(ids,wmNews.getId(),(short)1);
           }
       }
       //审核文章
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
       //将原有的直接调用自动审核的接口修改成添加到redis消息队列里面
        newsTaskService.addNewsToTask(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    /**
     * 文章的上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDownOrUpDto dto) {
        //1.检查参数
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.判断文章是否已发布
        if(wmNews.getStatus()!= 9){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }
        //4.修改文章enable
        wmNews.setEnable(dto.getEnable().intValue());
        wmNewsMapper.updateById(wmNews);
        if(wmNews.getArticleId() != null ){
            Map<String,Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", dto.getEnable());
     //发送消息到kafka
         kafkaTemplate.send("articleDownOrUpTopic",JSON.toJSONString(map));
        }
          return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}





